const config = {
  //baseUrl: 'http://localhost:8090/', 
  baseUrl: 'https://miniprogram.douyi.info:8091/',
  header: {
      'Content-Type': 'application/json'
  },
  timeout: 10000 
};

const requestInterceptor = {
  invoke(args) {
      args.url = config.baseUrl + args.url;
      const token = wx.getStorageSync('token');
      if (token) {
          args.header = {
             ...args.header,
              'Authorization': `Bearer ${token}`
          };
      }
      console.log('Request Interceptor Args:', args); // 打印请求参数
      if (!args.hideLoading) {
          wx.showLoading({
              title: '加载中...',
              mask: true
          });
      }
      return args;
  }
};

const responseInterceptor = {
  success(response) {
      wx.hideLoading();
      console.log('Response Success:', response); // 打印响应数据
      const { statusCode, data } = response;
      if (statusCode === 200) {
          if (data.code === 200) { 
              return Promise.resolve(data.data); 
          } else {
              return Promise.reject(data.message || '请求失败');
          }
      } else {
          return Promise.reject(`请求失败，状态码：${statusCode}`);
      }
  },
  fail(error) {
      wx.hideLoading();
      console.error('Response Fail:', error); // 打印错误信息
      return Promise.reject(error.errMsg || '网络错误，请稍后重试');
  }
};

const request = (options) => {
  options = requestInterceptor.invoke(options);
  return new Promise((resolve, reject) => {
      wx.request({
         ...options,
          success: (res) => {
              responseInterceptor.success(res)
                 .then(resolve)
                 .catch(reject);
          },
          fail: (err) => {
              responseInterceptor.fail(err)
                 .catch(reject);
          },
          complete: () => {
              if (!options.hideLoading) {
                  wx.hideLoading();
              }
          }
      });
  });
};

const http = {
  get(url, params = {}, options = {}) {
      return request({
          url,
          method: 'GET',
          data: params,
         ...options
      });
  },
  post(url, data = {}, options = {}) {
      return request({
          url,
          method: 'POST',
          data,
         ...options
      });
  }
};

module.exports = http;    